package com.abase.site.server.servlet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.abase.site.client.services.PocAbaseService;
import com.abase.site.server.CookieHelper;
import com.abase.site.server.ServiceFactory;
import com.abase.site.shared.AbaseException;
import com.abase.site.shared.AbaseException.AbaseExcpetionCodes;
import com.abase.site.shared.constants.AbaseConstants;
import com.abase.site.shared.login.LoginRequest;
import com.abase.site.shared.login.LoginResponse;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class AbaseAuthentificationServlet extends RemoteServiceServlet implements PocAbaseService {

	public LoginResponse doLogin(LoginRequest request) throws AbaseException {
		
		LoginResponse response = null;
		
		if (!request.isSimpleCheck()) {
			response = ServiceFactory.getInstance().getAbaseService().doLogin(request);
		} else {
			final HttpServletRequest httpRequest = getThreadLocalRequest();
			response = new LoginResponse();
			response.setAbaseProfile(CookieHelper.getCookie(httpRequest));
		}
		
		if (null == response.getAbaseProfile()) {
			throw new AbaseException(AbaseExcpetionCodes.ABASE_AUTH_LOGIN_FAIL);
		}
		response.setCookie(CookieHelper.getCookieValue(response.getAbaseProfile()));
	
		return response;
	}

}
